#include <WiFi.h>
#include <HTTPClient.h>
#include <ArduinoJson.h>

const char*ssid="Redmi Note 13 Pro+";
const char*password="raekd964";


// 2. Replace with your OpenAI API key
const char* spark_apiKey = "84937daeb42c357c67226209984acfd6";
const char* APISecret = "MGFmMTU4MWNkOTM0NTViZjk1M2UxZDk1";

// Send request to OpenAI API
String inputText = "请介绍下上面是函数，在85字以内";
String apiUrl = "https://spark-api-open.xf-yun.com/v1/chat/completions";

String answer;
String getGPTAnswer(String inputText) {
  HTTPClient http;
  http.setTimeout(20000);
  http.begin(apiUrl);
  String token_key = String("Bearer ") + spark_apiKey + String(":") + APISecret;
  http.addHeader("Authorization", token_key);
  http.addHeader("Content-Type", "application/json");
  String payload = "{\"model\":\"generalv3.5\",\"messages\":[{\"role\":\"system\",\"content\":\"1、你的回复只能包括两个部分：（开/关）+（房间位置）。例如“开卧室灯”、“关客厅灯”2、你要从我发给你的信息中提取我想说的指令，然后按照1回复，比如我会说“请打开卧室灯”，你按照1应当回复“开卧室灯”3、如果我不说（房间位置），那么房间位置默认为“客厅4.请严格按照1.的要求回复 不能包含任意的其他字符\"},{\"role\":\"user\",\"content\":\"" + inputText + "\"}]}";

  int httpResponseCode = http.POST(payload);
  if (httpResponseCode == 200) {
    String response = http.getString();
    http.end();
    Serial.println(response);

    // Parse JSON response
    DynamicJsonDocument jsonDoc(1024);
    deserializeJson(jsonDoc, response);
    String outputText = jsonDoc["choices"][0]["message"]["content"];
    return outputText;
    // Serial.println(outputText);
  } else {
    http.end();
    Serial.printf("Error %i \n", httpResponseCode);
    return "<error>";
  }
}

void setup() {
  // Initialize Serial
  Serial.begin(115200);

  // Connect to Wi-Fi network
  WiFi.mode(WIFI_STA);
  WiFi.begin(ssid, password);
  Serial.print("Connecting to WiFi ..");
  while (WiFi.status() != WL_CONNECTED) {
    Serial.print('.');
    delay(1000);
  }
  Serial.println(WiFi.localIP());

}

void loop() {
  // do nothing
  if (Serial.available()) {
    inputText = Serial.readStringUntil('\r');//  \r表示结束符为回车符
    // inputText.trim();
    Serial.println("\n Input:"+inputText);

    answer = getGPTAnswer(inputText);
    Serial.println("Answer: " + answer);
if(answer=="开客厅灯")Serial.println("OPEN LIVING ROOM LIGHT");


    Serial.println("Enter a prompt:");
  }
}
